/**
 * 
 */
package cn.jhz.filesharingsystem.service;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.jhz.filesharingsystem.dao.RoleDao;
import cn.jhz.filesharingsystem.dao.UserDao;
import cn.jhz.filesharingsystem.model.Pager;
import cn.jhz.filesharingsystem.model.User;
import cn.jhz.filesharingsystem.util.SecurityUtil;

/**
 * @author asus
 *
 */
@Service("userService")
public class UserServiceImpl extends BaseServiceImpl<User> implements UserService {

	@Autowired
	private RoleDao roleDao;
	
	@Override
	public void updateUser(User user) {
		int userid = user.getId();
		User userDB = baseDao.load(userid); 
		//load从数据库拿到预修改的用户记录对应的user对象，这个user对象就会直接进入到hibernate的一个缓存里
		userDB.setRegDate(user.getRegDate());
		userDB.setRole(user.getRole());
		userDB.setState(user.getState());
		if(user.getPassword()==null || "".equals(user.getPassword())) {
			
		}else {
			userDB.setPassword(SecurityUtil.md5$sha_x(user.getEmail(),user.getPassword()));
		}
		
		baseDao.update(userDB);
	}
	
	
	@Override
	public List<User> getAllUsers() {
		return ((UserDao)baseDao).getAllUsers();
	}

	@Override
	public Pager<User> getAllPagerUsers(String username, boolean state) {
		return ((UserDao)baseDao).getAllPagerUsers(username, state);
	}

	@Override
	public User login(String email, String password) {
		//根据传过来的username去数据库找找，有没有对应记录
		User user = ((UserDao)baseDao).loadUserByEmail(email);
		if(user == null) throw new RuntimeException("用户名或密码有误！");
		if(!user.getPassword().equals(SecurityUtil.md5$sha_x(email, password))) throw new RuntimeException("用户名或密码有误！");
		if(user.getState() != 1) throw new RuntimeException("该用户已被禁用！");
		return user;
	}


	@Override
	public User login(String account) {
		
		return ((UserDao)baseDao).loadUserByEmail(account);
	}


	@Override
	public User register(String username, String password, String email) {
		
		User newUser = new User();
		if(((UserDao)baseDao).loadUserByEmail(email)!=null)throw new RuntimeException("邮箱已被注册");
		if(((UserDao)baseDao).loadUserByUserName(username)!=null)throw new RuntimeException("用户名已被使用");
		
		newUser.setEmail(email);
		newUser.setUsername(username);
		newUser.setPassword(SecurityUtil.md5$sha_x(email, password));
		newUser.setRegDate(new Date());
		newUser.setState(1);
		newUser.setRole(roleDao.getRoleByName("guest"));
		
		
		return (add(newUser));
	}
	
}
